package com.example.smartcity.search;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;


import com.example.smartcity.R;

import java.util.List;

public class SearchHistoryAdapter extends RecyclerView.Adapter<SearchHistoryAdapter.SearchHistoryViewHolder> {

    private final List<String> searchHistoryList;
    private final OnItemClickListener listener;

    public interface OnItemClickListener {
        void onItemClick(String item);
    }

    public SearchHistoryAdapter(List<String> searchHistoryList, OnItemClickListener listener) {
        this.searchHistoryList = searchHistoryList;
        this.listener = listener;
    }

    public class SearchHistoryViewHolder extends RecyclerView.ViewHolder {
        public TextView tvSearchHistory;

        public SearchHistoryViewHolder(View view, final OnItemClickListener listener) {
            super(view);
            tvSearchHistory = (TextView) view.findViewById(R.id.tv_search_history);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        listener.onItemClick(searchHistoryList.get(position));
                    }
                }
            });
        }

        public void bind(String history) {
            tvSearchHistory.setText(history);
        }
    }

    @Override
    public SearchHistoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_search_history, parent, false);
        return new SearchHistoryViewHolder(itemView, listener);
    }

    @Override
    public void onBindViewHolder(SearchHistoryViewHolder holder, final int position) {
        String history = searchHistoryList.get(position);
        holder.bind(history);
    }

    @Override
    public int getItemCount() {
        return searchHistoryList != null ? searchHistoryList.size() : 0;
    }

    public void updateData(List<String> newData) {
        searchHistoryList.clear();
        searchHistoryList.addAll(newData);
        notifyDataSetChanged();
    }
}